import { Button, Card, Input, message, Select, Table } from 'antd'
import React, { Component, Fragment } from 'react'
import Linkbutton from '../../components/link-button'
import { getproductlist, updateStatus, searchproduct } from '../../api/index'
import memoryUtils from '../../utils/memoryUtils'
const Option = Select.Option
export default class home extends Component {
  state = {
    // 表格loading标识
    loading: true,
    // 表格数据
    dataSource: [],
    // 表格总数
    total: 0,
    // 当前页
    pageNum: this.props.location.state === undefined ? 1 : this.props.location.state.pageNum,
    // 每页条数
    pageSize: this.props.location.state === undefined ? 5 : this.props.location.state.pageSize,
    // 搜索模式
    searchtype: 'productName',
    // 搜索状态表示
    search: false,
    // 名字关键字
    productName: '',
    // 描述关键字
    productDesc: '',
  }
  // 表头
  columns = [
    {
      title: '商品名称',
      dataIndex: 'name',
      width: '20%'
    },
    {
      title: '商品描述',
      dataIndex: 'desc',
      width: '40%'
    },
    {
      title: '价格',
      dataIndex: 'price',
      width: '10%',
      render: (price) => '¥' + price
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: '10%',
      render: (status, record, index) => (
        <Fragment>
          <Button type='primary' danger={status === 1 ? false : true} onClick={this.updateStatus(record, index)}>{status === 1 ? '下架' : '上架'}</Button>
          <br />{status === 1 ? '在售' : '已下架'}
        </Fragment>

      )
    },
    {
      title: '操作',
      // dataIndex: '',
      key: 'lock',
      render: (data) =>
        <Fragment>
          <Linkbutton onClick={this.showdetail({
            ...data, pageNum: this.state.pageNum
            , pageSize: this.state.pageSize
          })}>详情</Linkbutton>&nbsp;
          <Linkbutton onClick={this.showupdate({
            ...data, pageNum: this.state.pageNum,
            pageSize: this.state.pageSize
          })}>修改</Linkbutton>
        </Fragment>
    },
  ];
  // 关键字输入框ref
  inputref = React.createRef();
  /**获取指定页码商品列表
   * @param {Number} pageNum:页码
   * @param {Number} pageSize:每页条数
   */
  showdetail(product) {
    return () => {
      memoryUtils.product = product
      this.props.history.push('/product/detail')
    }
  }
  showupdate(product) {
    return () => {
      memoryUtils.product = product
      this.props.history.push('/product/addupdate')
    }
  }
  getproducts = async (pageNum, pageSize) => {
    this.setState({ loading: true })
    let result = await getproductlist(pageNum, pageSize)
    if (result.status === 0) {
      const { list, total, pageNum } = result.data
      this.setState({ dataSource: list, loading: false, total: total, pageNum, pageSize })
    }
  }
  /**表格行内回调：更新商品状态
   */
  updateStatus = (record, index) => {
    return async () => {
      const result = await updateStatus(record._id, record.status === 0 ? 1 : 0)
      if (result.status === 0) {
        let newdataSource = this.state.dataSource
        newdataSource[index].status = newdataSource[index].status === 0 ? 1 : 0
        this.setState({ dataSource: newdataSource })
      }
    }
  }
  /**每页条数改变的回调
   */
  SizeChange = (current, pageSize) => {
    this.setState({ pageSize },
      () => {
        if (this.state.search === false) {
          this.getproducts(1, pageSize)
        } else {
          this.searchproduct(1)
        }
      }
    )

  }
  /**页码改变的回调
  */
  onChange = (pageNum, pageSize) => {
    if (this.state.search === false) {
      this.getproducts(pageNum, pageSize)
    } else {
      this.searchproduct(pageNum)
    }
  }
  /**搜索条件下，获取商品列表
   */
  searchproduct = async (pageNum) => {
    const { pageSize, productName, productDesc } = this.state
    this.setState({ loading: true })
    const { status, data: { list, total } } = await searchproduct({
      pageNum, pageSize,
      productName,
      productDesc,
    })
    if (status !== 0) {
      message.error('搜索失败！')
      this.setState({ loading: false })
    } else if (list.length === 0) {
      message.error(`没有找到,请重新输入关键字！`)
      this.inputref.current.state.value = ''
      this.getproducts(1, pageSize)
    } else {
      this.setState({ search: true, dataSource: list, loading: false, total: total, pageNum, pageSize })
    }
  }
  /**搜索按钮事件
  */
  searchproduct_one = (pageNum) => {
    return () => {

      let { value } = this.inputref.current.state
      const { searchtype } = this.state
      if (value === undefined) {
        value = ''
      }
      value = value.trim()
      if (value === '') {
        value = null
      }
      let productName = searchtype === 'productName' ? value : null
      let productDesc = searchtype === 'productDesc' ? value : null
      if (productName === null && productDesc === null) {
        return message.error('请输入关键字！')
      }
      this.setState({ productName, productDesc }, () => {
        this.searchproduct(pageNum)
      })

    }
  }
  /**重置表格，取消搜索
  */
  reset = () => {
    this.inputref.current.state.value = ''
    this.setState({ search: false }, () => {
      this.getproducts(1, this.state.pageSize)
    })
  }

  componentDidMount() {
    this.getproducts(this.state.pageNum, this.state.pageSize)
  }
  render() {
    const title = (
      <Fragment>
        <Select style={{ width: 150 }} defaultValue={'productName'}
          onSelect={(LabeledValue, option) => { this.setState({ searchtype: LabeledValue }) }}
        >
          <Option value='productName'>按名称搜索</Option>
          <Option value='productDesc'>按描述搜索</Option>
        </Select>
        &nbsp;
        <Input style={{ width: 150 }} placeholder='关键字'
          ref={this.inputref}
        ></Input>
        &nbsp;
        <Button type='primary' onClick={this.searchproduct_one(1)}>搜索</Button>
        <Button type='primary' style={{ marginLeft: '5px' }} onClick={this.reset}>重置</Button>
      </Fragment>

    )
    const extra = (
      <Button type='primary' onClick={this.showupdate({ pageNum: this.state.pageNum, pageSize: this.state.pageSize })}>添加商品</Button>
    )
    const { loading, dataSource, total, pageSize, pageNum } = this.state
    return (
      <Card style={{ height: '100%', overflow: 'auto' }}
        title={title} extra={extra} >
        <Table pagination={{
          current: pageNum,
          showSizeChanger: true,
          pageSizeOptions: ['3', '5', '7', '9', '20'],
          defaultCurrent: 1,
          total: total,
          showTotal: (total, range) => {
            return `共 ${total} 件`
          },
          responsive: false,
          defaultPageSize: pageSize,
          onShowSizeChange: this.SizeChange,
          onChange: this.onChange,
          showQuickJumper: { goButton: (<Fragment>&nbsp;&nbsp;<Button type='primary' >跳转</Button></Fragment>) }
        }}
          rowKey='_id' bordered dataSource={dataSource}
          columns={this.columns}
          loading={loading}
        />
      </Card>
    )
  }
}
